from peewee import *
from datetime import datetime
from common.enum.strategy_group_enum import StrategyGroup
from common.enum.strategy_type_enum import StrategyType
from dto.strategy_info import StrategyInfoMetadata
from service.das.database_pool import DatabasePool


# 数据模型定义
class StrategyInfoModel(Model):
    # 策略代码
    strategy_code = CharField(max_length=50, unique=True)
    # 策略名称
    strategy_name = CharField(max_length=100)
    # 策略分组
    strategy_group = IntegerField()
    # 策略类型
    strategy_type = IntegerField()
    # 分析天数
    analysis_day = IntegerField()
    # 策略等级
    strategy_level = IntegerField()
    # 是否启用
    is_enabled = BooleanField(default=True)
    # 创建时间
    created_at = DateTimeField(default=datetime.now)
    # 更新时间
    updated_at = DateTimeField(default=datetime.now)

    class Meta:
        database = DatabasePool(max_connections=5).database
        table_name = "strategy_info"


# 服务类
class StrategyManagementService:

    def add_strategy(self, metadata: StrategyInfoMetadata, is_enabled: bool = True):
        """
        添加新的策略记录。
        """
        try:
            StrategyInfoModel.create(
                strategy_code=metadata.strategy_code,
                strategy_name=metadata.strategy_name,
                strategy_group=metadata.strategy_group.value,
                strategy_type=metadata.strategy_type.value,
                analysis_day=metadata.analysis_day,
                strategy_level=metadata.strategy_level,
                is_enabled=is_enabled,
            )
            AntLogger.info(f"策略 {metadata.strategy_name} 已添加。")
        except IntegrityError:
            AntLogger.info(f"策略代码 {metadata.strategy_code} 已存在，无法重复添加。")
        except Exception as e:
            AntLogger.info(f"添加策略时出错: {e}")

    def update_strategy(self, strategy_code: str, updated_info: dict):
        """
        更新策略信息。
        """
        try:
            strategy = StrategyInfoModel.get(
                StrategyInfoModel.strategy_code == strategy_code
            )
            if "strategy_name" in updated_info:
                strategy.strategy_name = updated_info["strategy_name"]
            if "strategy_group" in updated_info:
                strategy.strategy_group = updated_info["strategy_group"].value
            if "strategy_type" in updated_info:
                strategy.strategy_type = updated_info["strategy_type"].value
            if "analysis_day" in updated_info:
                strategy.analysis_day = updated_info["analysis_day"]
            if "strategy_level" in updated_info:
                strategy.strategy_level = updated_info["strategy_level"]
            if "is_enabled" in updated_info:
                strategy.is_enabled = updated_info["is_enabled"]

            strategy.updated_at = datetime.now()
            strategy.save()
            AntLogger.info(f"策略 {strategy_code} 已更新。")
        except DoesNotExist:
            AntLogger.info(f"未找到策略代码为 {strategy_code} 的记录。")
        except Exception as e:
            AntLogger.info(f"更新策略时出错: {e}")

    def delete_strategy(self, strategy_code: str):
        """
        删除策略记录。
        """
        try:
            strategy = StrategyInfoModel.get(
                StrategyInfoModel.strategy_code == strategy_code
            )
            strategy.delete_instance()
            AntLogger.info(f"策略 {strategy_code} 已删除。")
        except DoesNotExist:
            AntLogger.info(f"未找到策略代码为 {strategy_code} 的记录。")
        except Exception as e:
            AntLogger.info(f"删除策略时出错: {e}")
    def delete_all_strategy_info(self):
        """
        删除所有策略记录。
        """
        try:
            deleted_count = StrategyInfoModel.delete().execute()
            AntLogger.info(f"已删除 {deleted_count} 条策略记录。")
        except Exception as e:
            AntLogger.info(f"删除所有策略时出错: {e}")

    def get_all_strategies(self):
        """
        获取所有策略记录。
        """
        try:
            strategies = StrategyInfoModel.select()
            return list(strategies)
        except Exception as e:
            AntLogger.info(f"获取策略列表时出错: {e}")
            return []

    def get_strategy_by_code(self, strategy_code: str) -> StrategyInfoModel:
        """
        根据策略代码查询策略记录。
        """
        try:
            strategy = StrategyInfoModel.get(
                StrategyInfoModel.strategy_code == strategy_code
            )
            return strategy
        except DoesNotExist:
            AntLogger.info(f"未找到策略代码为 {strategy_code} 的记录。")
            return None
        except Exception as e:
            AntLogger.info(f"查询策略时出错: {e}")
            return None
